/***************************************************************************************
 The copyright in this software is being made available under the BSD License, included
 below. This software may be subject to other third party rights,including patent rights,
 and no such rights are granted under this license.

 Regents of the Tsinghua University, Peking University, Zhejiang University, HKUST
 Tsinghua University, Peking University, Zhejiang University, HKUST 2011

 Copyright (c) 2011, Regents of the Tsinghua University, Peking University, Zhejiang
 University, HKUST. All Rights Reserved.

 Redistribution and use in source and binary forms, with or without modification, are
 permitted provided that the following conditions are met:
   * Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.
   * Neither the names of the copyright holders nor the names of its
     contributors may be used to endorse or promote products derived from this
     software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 OF SUCH DAMAGE.
***************************************************************************************/

/**************************************************************************************
* File name: golomb_dec.c
* Function: Description
*
*************************************************************************************
*/

#include <assert.h>

#include "contributors.h"
#include "golomb_dec.h"
#include "global.h"

extern bbv_buffer_t *pBbv;

#if TRACE
/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void encode_golomb_word( unsigned int symbol, unsigned int grad0, unsigned int max_levels, unsigned int *res_bits, unsigned int *res_len )
{
    unsigned int level, res, numbits;
    res = 1UL << grad0;
    level = 1UL;
    numbits = 1UL + grad0;
    //find golomb level
    while ( symbol >= res && level < max_levels )
    {
        symbol -= res;
        res = res << 1;
        level++;
        numbits += 2UL;
    }
    if ( level >= max_levels )
    {
        if ( symbol >= res )
            symbol = res - 1UL;
    }
    //set data bits
    *res_bits = res | symbol;
    *res_len = numbits;

}

void encode_multilayer_golomb_word( unsigned int symbol, const unsigned int *grad, const unsigned int *max_levels, unsigned int *res_bits, unsigned int *res_len )
{
    unsigned accbits, acclen, bits, len, tmp;
    accbits = acclen = 0UL;
    while ( 1 )
    {
        encode_golomb_word( symbol, *grad, *max_levels, &bits, &len );
        accbits = ( accbits << len ) | bits;
        acclen += len;
        assert( acclen <= 32UL );   //we'l be getting problems if this gets longer than 32 bits.
        tmp = *max_levels - 1UL;
        if ( !( ( len == ( tmp << 1 ) + ( *grad ) ) && ( bits == ( 1UL << ( tmp + *grad ) ) - 1UL ) ) ) //is not last possible codeword? (Escape symbol?)
            break;
        tmp = *max_levels;
        symbol -= ( ( ( 1UL << tmp ) - 1UL ) << ( *grad ) ) - 1UL;
        grad++;
        max_levels++;
    }
    *res_bits = accbits;
    *res_len = acclen;
}
#endif

unsigned int decode_golomb_word( unsigned char **buffer, unsigned int *bitoff, unsigned int grad0, unsigned int max_levels )
{
    unsigned char *rd;
    unsigned int bit, byte, level, databits, t, testbit;
    rd = *buffer;
    bit = *bitoff;
    byte = *rd;
    level = 0UL;
    while ( level < max_levels )  //( level+1UL<max_levels )
    {
        testbit = byte & ( 1UL << bit );
        bit = ( bit - 1UL ) & 7UL;
        if ( bit == 7UL )
            byte = *( ++rd );
        if ( testbit )
            break;
        level++;
    }
    databits = 0UL;
    for ( t = 0UL; t < ( grad0 + level ); t++ )
    {
        databits = ( databits << 1UL ) | ( ( byte >> bit ) & 1UL );
        bit = ( bit - 1UL ) & 7UL;
        if ( bit == 7UL )
            byte = *( ++rd );
    }
    *buffer = rd;
    *bitoff = bit;
    return ( ( ( 1UL << level ) - 1UL ) << grad0 ) + databits;
}

unsigned int decode_multilayer_golomb_word( unsigned char **buffer, unsigned int *bitoff, const unsigned int *grad0, const unsigned int *max_levels )
{
    unsigned int symbol, partsymbol, tmp;
    symbol = 0UL;
    while ( 1 )
    {
        partsymbol = decode_golomb_word( buffer, bitoff, *grad0, *max_levels );
        symbol += partsymbol;
        tmp = *max_levels;
        if ( partsymbol < ( ( ( 1UL << tmp ) - 1UL ) << ( *grad0 ) ) - 1UL ) //not escape symbol?
            break;
        grad0++;
        max_levels++;
    }
    return symbol;
}

int readSyntaxElement_GOLOMB( syntax_element_t * se, image_t *img, input_t *inp )
{
    int frame_bitoffset;
    unsigned char *buf, *read;
    unsigned int bit, i;
    unsigned int grad[4], max_lev[4];

#if TRACE
    unsigned int len;
#endif

    frame_bitoffset = currStream->frame_bitoffset;
    buf = ( unsigned char * )currStream->stream_buffer;

    bit = 7UL - ( frame_bitoffset & 7 );
    read = buf + ( frame_bitoffset >> 3 );

    if ( !( se->golomb_maxlevels & ~0xFF ) )
    {
        se->value1 = decode_golomb_word( &read, &bit, se->golomb_grad, se->golomb_maxlevels );
    }
    else
    {
        for ( i = 0UL; i < 4UL; i++ )
        {
            grad[i] = ( se->golomb_grad >> ( i << 3 ) ) & 0xFFUL;
            max_lev[i] = ( se->golomb_maxlevels >> ( i << 3 ) ) & 0xFFUL;
        }
        se->value1 = decode_multilayer_golomb_word( &read, &bit, grad, max_lev );
    }

    se->len = ( ( ( read - buf ) << 3 ) + ( 7 - bit ) ) - frame_bitoffset;

#if TRACE
    if ( !( se->golomb_maxlevels & ~0xFF ) ) //only bits 0-7 used? This means normal Golomb word.
        encode_golomb_word( se->value1, se->golomb_grad, se->golomb_maxlevels, &( se->value2 ), &len );
    else
    {
        for ( i = 0UL; i < 4UL; i++ )
        {
            grad[i] = ( se->golomb_grad >> ( i << 3 ) ) & 0xFFUL;
            max_lev[i] = ( se->golomb_maxlevels >> ( i << 3 ) ) & 0xFFUL;
        }
        encode_multilayer_golomb_word( se->value1, grad, max_lev, &( se->value2 ), &len );
    }

    tracebits3( "", se->len, se->value2, se->value1 );
#endif

    se->value2 = 0;
    currStream->frame_bitoffset += se->len;

    if ( input->check_BBV_flag && pBbv )
    {
        pBbv->frame_code_bits += se->len;
    }

    return 1;
}
